<script lang="ts">
import type { SetRequired } from 'type-fest';
import bignumber, { type BigNumber } from '@peng_kai/kit/libs/bignumber';
import { cloneDeep } from '@peng_kai/kit/libs/lodash-es';
import { useStorage } from '@peng_kai/kit/libs/vueuse';
import { lockRecordPopup } from '~/components-business/global-popups/newWallet/Comps/LockRecord/index.vue';

interface TCurrency {
  currency: string;
  balance?: string;
  bonus_balance?: string;
  locked_balance?: string;
  locked_balance_detail?: {
    deposit_bet_amount: string;
    completed_bet_amount: string;
    status: number;
  };
}

function hasBonusBalance(currency: TCurrency): currency is SetRequired<
  TCurrency,
  'bonus_balance' | 'locked_balance' | 'locked_balance_detail'
> {
  return !!(bignumber(currency?.bonus_balance ?? 0).gt(0) && currency.locked_balance && currency.locked_balance_detail);
}

function isUnlocked(currency: TCurrency) {
  if (!currency.locked_balance_detail)
    return false;

  return bignumber(currency.locked_balance_detail.completed_bet_amount).gte(currency.locked_balance_detail.deposit_bet_amount);
}
</script>

<script setup lang="ts">
const props = withDefaults(defineProps<{
  currencyList?: TCurrency[];
  showBalance?: boolean;
  showHideZeroBalanceBtn?: boolean;
  showConvertToFiatBtn?: boolean;
  listClass?: string;
}>(), {
  showBalance: true,
  showHideZeroBalanceBtn: true,
  showConvertToFiatBtn: true,
});

const emits = defineEmits(['close']);
const value = defineModel<string | null | undefined>('value', { default: undefined });

const currencyStore = useCurrencyStore();
const { quote, quoteDisplay, quoteName, crypto } = storeToRefs(currencyStore);
const hideZeroBalance = useStorage('HIDE_ZERO_BALANCE', false);
const keyword = ref('');
const showQuotePopup = useBoolean();
const quoteSymbol = computed(() => quoteDisplay.value ? quote.value?.symbol : undefined);
const currencyList = computed(() => {
  const _keyword = keyword.value;
  const _hideZeroBalance = hideZeroBalance.value;
  const _currencyList = props.currencyList || useCurrencyStore().balanceList;

  if (!_currencyList)
    return undefined;

  let filterdCurrency = cloneDeep(_currencyList);

  if (_keyword)
    filterdCurrency = filterdCurrency.filter(item => item.currency.trim().toUpperCase().includes(_keyword.toUpperCase()));

  if (_hideZeroBalance)
    filterdCurrency = filterdCurrency.filter(item => item.currency === crypto.value?.currency || item.balance !== '0');

  return filterdCurrency;
});

function convertValue(sourceCurrency: string, sourceValue: BigNumber.Value) {
  if (quoteDisplay.value)
    return currencyStore.convert(sourceCurrency, sourceValue, quoteName.value);

  return bignumber(sourceValue);
}

function openClaim() {
  const { bonuses } = queries.useBonusesQuery();
  const bonus = bonuses.value?.bonus;
  const bonusesDetails = bonus?.bonuses_details;
  const canClaim = !!(bonus && bonusesDetails?.length);

  if (canClaim) {
    const currency = bonusesDetails.map((c: any) => ({ symbol: c.currency, amount: bignumber(c.balance) }));
    globalPopups.claim.open({
      amount: Number(bonus?.amount),
      claimType: bonus.bonuses_type,
      currency,
    });
  }
}

const searchDomRef = ref();

defineExpose({ focusSearch: () => searchDomRef.value?.focus?.() });
</script>

<template>
  <div>
    <AInput
      ref="searchDomRef"
      v-model:value="keyword" class="w-full text-sm"
      allowClear
      :placeholder="$t('kWtinSdSl8OQfahLfF0il')"
    >
      <template #prefix>
        <i class="i-local:search text-sys-text-body" />
      </template>
    </AInput>

    <!-- 币种列表 -->
    <div
      v-if="currencyList"
      class="currency-list mt-3 min-h-30 overflow-y-auto overscroll-none text-sys-text-body font-600"
      :class="listClass"
    >
      <div
        v-for="(item, i) in currencyList" :key="i"
        class="flex cursor-pointer items-center py-1.5 text-4 hover:text-sys-text-head"
        @click="[value = item.currency, emits('close')]"
      >
        <TCurrencyIcon class="mr-2 transform-origin-left-center" :symbol="item.currency" />
        <span class="mr-auto">{{ item.currency }}</span>

        <div v-if="props.showBalance" class="text-right text-xs">
          <div class="transform-origin-bottom-right scale-110 text-sys-text-head">
            <!-- 测试币不用转计价 -->
            <TAmount
              :value="convertValue(item.currency, bignumber(item.balance ?? 0).minus(item.bonus_balance ?? 0))"
              :symbol="item.currency === TEST_CURRENCY ? undefined : quoteSymbol"
              iconType="text" :decimals="7" format="pad-dec" iconPos="left"
            />
          </div>
          <!-- 锁定金额 -->
          <ATooltip
            v-if="hasBonusBalance(item)"
            :open="$bp.ltMobilel ? false : undefined"
            trigger="hover"
            overlayClassName="text-xs" placement="topRight"
          >
            <template #title>
              <span>
                {{ $t('mzDhmaivuOccvVlWlamUa') }} (<TAmount
                  :value="convertValue(item.currency, item.locked_balance_detail.completed_bet_amount)"
                  :symbol="quoteSymbol" :decimals="2" format="pad-dec" iconPos="left"
                />/<TAmount
                  :value="convertValue(item.currency, item.locked_balance_detail.deposit_bet_amount)"
                  :symbol="quoteSymbol" :decimals="2" format="pad-dec" iconPos="left"
                />)
              </span>
            </template>
            <div
              class="relative mt-1 flex items-center justify-end text-sys-text-head font-400"
              @click="item.locked_balance_detail.status === 3 ? openClaim() : lockRecordPopup?.open({ type: 2 })"
            >
              <img
                src="../../assets/imgs/user/gift.png"
                class="block size-1em"
                :class="{ 'jump-shake': item.locked_balance_detail.status === 3 }"
              >
              <TAmount
                :value="convertValue(item.currency, item.bonus_balance)"
                :symbol="quoteSymbol" :decimals="2" format="pad-dec" iconPos="left"
              />
              <!-- 扩大可点击范围 -->
              <div class="absolute bottom-0 right-0 h-8 w-24" />
            </div>
          </ATooltip>
        </div>
      </div>
    </div>

    <!-- 操作 -->
    <div class="grid mt-3 gap-3 border-t-(1 sys-layer-e solid) pt-3 text-sm empty:hidden">
      <div v-if="props.showHideZeroBalanceBtn" class="flex items-center justify-between">
        <span>{{ $t('pgGsRmQjQcxUk6TLxinyX') }}</span>
        <ASwitch v-model:checked="hideZeroBalance" />
      </div>

      <div v-if="props.showConvertToFiatBtn" class="flex items-center">
        <span class="mr-auto">{{ $t('lhOaWrTQl9zwa6qfXvXp') }}</span>
        <div
          class="mr-2 h-7 flex cursor-pointer items-center justify-center gap-[2px] rounded-[6px] bg-sys-layer-e px-2.5 text-sm"
          @click="showQuotePopup.setTrue()"
        >
          <TCurrencyIcon class="" :symbol="quote?.currency" /><span>{{ quote?.currency }}</span>
        </div>
        <ASwitch v-model:checked="quoteDisplay" />
      </div>
    </div>

    <!-- 计价币种选择 -->
    <AModal
      v-model:open="showQuotePopup.is"
      :title="$t('gNeZqkZmHAwgQky293Jgk')"
      wrapClassName="ant-cover__Modal-drawer" centered :footer="null"
    >
      <div class="h-full flex flex-col">
        <p class="mb-3 whitespace-pre-line text-3.5 text-sys-text-body leading-5">
          {{ $t('tablbKdqRslICk5fhwgLd') }}
        </p>
        <div class="grid grid-cols-4 flex-1 gap-2 overflow-y-auto overscroll-none pr-2 -mr-2">
          <div
            v-for="fiat in currencyStore.fiatList" :key="fiat.currency"
            class="flex cursor-pointer items-center justify-center rounded-2 bg-slate700 py-2.5 text-sys-text-body hover:text-sys-text-head"
            @click="[quoteName = fiat.currency, showQuotePopup.setFalse()]"
          >
            <TCurrencyIcon class="button-icon mr-1 block size-6 lt-mobile:(size-5)" :symbol="fiat.currency" />
            <span class="button-text text-4" u:lt-mobile="text-3.5">{{ fiat.currency }}</span>
          </div>
        </div>
      </div>
    </AModal>

    <lockRecordPopup.PresetComponent />
  </div>
</template>

<style lang="scss" scoped>
.currency-list {
  @supports (scrollbar-gutter: stable) {
    scrollbar-gutter: stable;
    margin-right: -8px;
    padding-right: 8px;
  }

  @media (hover: none) {
    scrollbar-gutter: auto;
  }
}
</style>
